<?php

namespace App\Modules\Admin\Services;

use App\Exceptions\Exception;
use App\Exceptions\InvalidRequestException;
use App\Models\Dynamic\Dynamic;
use App\Models\Log\AdminLog;
use Illuminate\Support\Facades\DB;

class DynamicService extends BaseService
{
    public function __construct(Dynamic $dynamic)
    {
        $this->model = $dynamic;
        $this->with = ['userInfo', 'topic'];
        $this->detailWith = ['userInfo', 'topic'];
    }

    public function lists(array $params) : array
    {
        $params['where_callback'] = function($query) use ($params){
            $request = request();
            // 按照名称进行搜索
            if (!empty($search = $request->input('search', ''))){
                $search = trim($search);
                $query->where(function($query)use ($search){
                    $query->where('dynamic_title', 'LIKE', '%' . $search . '%')
                          ->orWhere('dynamic_content', 'LIKE', $search . '%')
                          ->orWhere('dynamic_markdown', 'LIKE', $search . '%');
                });
            }
            // 话题筛选
            $topic_id = $request->input('topic_id', -1);
            if ($topic_id > -1){
                $query->whereIn('topic_id', $topic_id);
            }
            // 审核
            $is_check = $request->input('is_check', -1);
            if ($is_check > -1){
                $query->where('is_check', '=', $is_check);
            }
            // 是否公开
            $is_public = $request->input('is_public', -1);
            if ($is_public > -1){
                $query->where('is_public', '=', $is_public);
            }
            // 置顶
            $set_top = $request->input('set_top', -1);
            if ($set_top > -1){
                $query->where('set_top', '=', $set_top);
            }
            // 推荐|加精
            $excellent_time = $request->input('excellent_time', -1);
            if ($excellent_time > 0){
                $query->where('excellent_time', '>', $excellent_time);
            }
        };
        return parent::lists($params); // TODO: Change the autogenerated stub
    }

    private function getDynamic(int $dynamic_id)
    {
        $dynamic = $this->model->find($dynamic_id);
        if (!$dynamic){
            throw new InvalidRequestException('动态已失效！');
        }
        return $dynamic;
    }


    /**
     * 审核动态
     *
     * @param  int  $admin_id
     * @param       $request
     *
     * @return bool
     * @throws \App\Exceptions\InvalidRequestException
     * @throws \Throwable
     */
    public function check(int $admin_id, $request): bool
    {
        $dynamic = $this->getDynamic($request->dynamic_id);
        if ($dynamic->is_check == 1){
            throw new InvalidRequestException('动态已审核通过！');
        }
        DB::beginTransaction();
        try{
            $dynamic->update([
                'is_check' => $request->is_check,
                'admin_remarks' => $request->admin_remarks,
            ]);

            // 操作日志
            AdminLog::addRecord($admin_id, '审核动态【' . $dynamic->dynamic_id . '】，设为‘' . ($request->is_check == 1 ? '通过' : '拒绝') . '’');

            DB::commit();
        }catch (Exception $e){
            DB::rollBack();
            throw new InvalidRequestException('审核失败，' . $e->getMessage());
        }
        return true;
    }

    /**
     * 动态`置顶`设置
     *
     * @param  int  $admin_id
     * @param       $request
     *
     * @return bool
     * @throws \App\Exceptions\InvalidRequestException
     * @throws \Throwable
     */
    public function setTop(int $admin_id, $request): bool
    {
        $dynamic = $this->getDynamic($request->dynamic_id);
        DB::beginTransaction();
        try{
            $dynamic->update([
                'set_top' => $request->set_top
            ]);

            // 操作日志
            AdminLog::addRecord($admin_id, '动态置顶操作【' . $dynamic->dynamic_id . '】，设为‘' . ($request->set_top == 1 ? '置顶' : '普通') . '’');

            DB::commit();
        }catch (Exception $e){
            DB::rollBack();
            throw new InvalidRequestException('置顶设置失败，' . $e->getMessage());
        }
        return true;
    }

    /**
     * 动态`加精`设置
     * @param  int  $admin_id
     * @param       $request
     *
     * @return bool
     * @throws \App\Exceptions\InvalidRequestException
     * @throws \Throwable
     */
    public function excellent(int $admin_id, $request): bool
    {
        $dynamic = $this->getDynamic($request->dynamic_id);
        $is_cancel = $request->is_cancel ? 0 : 1;
        DB::beginTransaction();
        try{
            $dynamic->update([
                'excellent_time' => $is_cancel == 1 ? 0 : time()
            ]);

            // 操作日志
            AdminLog::addRecord($admin_id, '动态加精操作【' . $dynamic->dynamic_id . '】，设为‘' . ($is_cancel == 0 ? '加精' : '普通') . '’');

            DB::commit();
        }catch (Exception $e){
            DB::rollBack();
            throw new InvalidRequestException('加精设置失败，' . $e->getMessage());
        }
        return true;
    }
}
